package com.ruoyi.tcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DeletedEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;

import com.ruoyi.tcp.domain.AddressUnit;
import com.ruoyi.tcp.mapper.AddressUnitMapper;
import com.ruoyi.tcp.service.IAddressUnitService;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 行政单位Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-22
 */
@Service
@Slf4j
public class AddressUnitServiceImpl extends ServiceImpl<AddressUnitMapper, AddressUnit> implements IAddressUnitService {
    @Autowired
    private AddressUnitMapper addressUnitMapper;


    @Autowired
    protected Validator validator;

    @Override
    public Page<AddressUnit> pageList(Page<AddressUnit> page, AddressUnit addressUnit) {
        LambdaQueryWrapper<AddressUnit> queryWrapper = getQueryWrapper(addressUnit);
        return page(page, queryWrapper);
    }

    @Override
    public List<AddressUnit> listAll(AddressUnit addressUnit) {
        return list(getQueryWrapper(addressUnit));
    }

    private LambdaQueryWrapper<AddressUnit> getQueryWrapper(AddressUnit addressUnit) {
        LambdaQueryWrapper<AddressUnit> queryWrapper = Wrappers.lambdaQuery(AddressUnit.class);
        queryWrapper.eq(AddressUnit::getDeleted, DeletedEnum.NOMAL.getValue());

//        父部门id
        if (Objects.nonNull(addressUnit.getParentId())) {
            queryWrapper.eq(AddressUnit::getParentId, addressUnit.getParentId());
        }


//        祖级列表
        if (StringUtils.isNotEmpty(addressUnit.getAncestors())) {
            queryWrapper.likeLeft(AddressUnit::getAncestors, addressUnit.getAncestors());
        }


//        名称
        if (StringUtils.isNotEmpty(addressUnit.getName())) {
            queryWrapper.like(AddressUnit::getName, addressUnit.getName());
        }


//        状态（0正常 1停用）
        if (StringUtils.isNotEmpty(addressUnit.getStatus())) {
            queryWrapper.eq(AddressUnit::getStatus, addressUnit.getStatus());
        }


        return queryWrapper;
    }

    @Override
    public int edit(AddressUnit addressUnit) {
        addressUnit.setUpdateBy(SecurityUtils.getUsername());
        addressUnit.setUpdateTime(new Date());
        AddressUnit newParentAddressUnit = addressUnitMapper.selectById(addressUnit.getParentId());
        AddressUnit oldAddressUnit = addressUnitMapper.selectById(addressUnit.getId());
        if (StringUtils.isNotNull(newParentAddressUnit) && StringUtils.isNotNull(oldAddressUnit)) {
            String newAncestors = newParentAddressUnit.getAncestors() + "," + newParentAddressUnit.getId();
            String oldAncestors = oldAddressUnit.getAncestors();
            addressUnit.setAncestors(newAncestors);
            updateDeptChildren(addressUnit.getId(), newAncestors, oldAncestors);
        }
        if (UserConstants.DEPT_NORMAL.equals(addressUnit.getStatus()) && StringUtils.isNotEmpty(addressUnit.getAncestors())
                && !StringUtils.equals("0", addressUnit.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentStatusNormal(addressUnit);
        }
        return addressUnitMapper.updateById(addressUnit);
    }

    private void updateParentStatusNormal(AddressUnit addressUnit) {
        String ancestors = addressUnit.getAncestors();
        Long[] ids = Convert.toLongArray(ancestors);
        AddressUnit updateData = new AddressUnit();
        updateData.setStatus("0");
        addressUnitMapper.update(updateData,Wrappers.<AddressUnit>lambdaUpdate().in(AddressUnit::getId, ids));
    }

    private void updateDeptChildren(Long id, String newAncestors, String oldAncestors) {
        LambdaQueryWrapper<AddressUnit> queryWrapper = Wrappers.lambdaQuery(AddressUnit.class).eq(AddressUnit::getParentId, id);
        List<AddressUnit> children = addressUnitMapper.selectList(queryWrapper);
        for (AddressUnit child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            addressUnitMapper.updateById(children);
        }
    }

}
